<?php
namespace app\index\controller;
use think\Db;
use think\Controller;
use Firebase\JWT\JWT;

/**
 * 公用基础控制器
 */
class Base extends Controller {

	protected $uid;

	protected function _initialize() {
		parent::_initialize();
        if(!session("1")){
        	session("1",1);
			session("openid",null);
			session("user_info",null);
        }
		$user=db('user')->find();
		
		session("user_info",$user);
		session("openid",$user['openid']);
        $cut_action = request()->action();
		$this->exist_user();
        $this->assign('action',request()->action());
		$this->assign('controller',request()->controller());
		
	}
	
	//判断会员是否存在并自动注册
	public function exist_user(){
		$user=session('user_info');
        $redirect='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        if(!$user) {
            $auth_code=input("code");
            $url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect';
            if(!$auth_code){
                Header("Location: $url");
                exit;
            }else{
                //$pay_type = 2;
                $union_info=get_userinfo($auth_code);
				$openid=$union_info['openid'];
				$data['nickname']=$union_info['nick_name'];
				$data['logo']=$union_info['headimgurl'];
				$data['openid']=$openid;
				session("openid",$openid);
            }
            $user_info = db('user')->where('openid',$openid)->find();
            if($user_info){
            	if($user_info['is_atten']==0){
            		$is_atten=is_atten($openid);
					if($is_atten){
						db('user')->where('openid',$openid)->update(['is_atten',1]);
						$user_info['is_atten']=1;
					}
            	}
                session('user_info', $user_info);
                //$this->redirect($redirect);
            }else{
            	if(input("tj_emp")){
            		$data['tj_emp']=input("tj_emp");
            	}
				$data['add_time']=now_time();
				$is_atten=is_atten($openid);
				$data['is_atten']=$is_atten;
                $res = db("user")->insert($data);
				if($res){
					$user=db('user')->where("openid",$openid)->find();
					session('user_info',$user);
				}else{
					$this->error('授权失败');
				}	
            }
       	}
	}


	protected function jwt_token($id, $mobile, $exp = '172800') {
		$nowtime = time();
		$token = array(
			'iss' => 'https://s.qiansuipay.com', //签发者
			'aud' => 'https://s.qiansuipay.com', //jwt所面向的用户
			'iat' => $nowtime, //签发时间
			'exp' => $nowtime + $exp, //过期时间-10min
			'data' => array(
				'id' => $id,
				'mobile' => $mobile 
			)
		);
		$jwt = JWT::encode($token, config('JWT_KEY'));
		return $jwt;
	}

	protected function check_token() {
		$json['msg'] = '';
		$json['error'] = false;
		$json['code'] = -1;
		//验证key,是否非法访问
		$jwt = isset($_SERVER['HTTP_TOKEN']) ? $_SERVER['HTTP_TOKEN'] : '';
		if (empty($jwt)) {
			$json['msg'] = 'Access No';
			$json['error'] = true;
		} else {
			try {
				JWT::$leeway = 60;
				$decoded = JWT::decode($jwt, config('JWT_KEY'), array('HS256'));
				$arr = (array)$decoded;
				if ($arr['exp'] < time()) {
					$json['msg'] = 'Token Expired';
					$json['error'] = true;
				}
				$this->uid = $arr['data']->id;
				$member = db('member')->where("id",$arr['data']->id)->find();
				//$member = db('member')->where('mobile', $mobile)->where('password', $password)->find();
				if (!$member) {
					$json['msg'] = '会员身份验证错误，强制下线';
					$json['error'] = true;
				} else {
					// 判断是否多点登录
					if ($member['token']!= $jwt) {
						$json['msg'] = '账号在别处登录您被强制下线了';
						$json['error'] = true;
					}
				}
			} catch(\Exception $e) {
				$json['msg'] = 'Token Failed';
				$json['error'] = true;
			}
		}
		if ($json['error']) {
			json($json)->send();
			exit ;
		}
	}

	/**
	 * 返回成功带提示信息
	 * @param msg 操作成功或操作失败
	 * @param error=false
	 */
	protected function toSuccess($msg = '操作成功', $data = '') {
		$json['msg'] = $msg;
		$json['data'] = $data;
		$json['code'] = 1;
		return json($json);
	}

	/**
	 * 返回失败带提示信息
	 * @param msg
	 * @param data 可以为空
	 * @param error=true
	 */
	protected function toError($msg = '没有查到数据') {
		$json['msg'] = $msg;
		$json['code'] = 0;
		return json($json);
	}

	/**
	 * 返回成功不带提示信息
	 * @param data
	 * @param error=false
	 */
	protected function toData($data) {
		$json['data'] = $data;
		$json['code'] = 1;
		return json($json);
	}
	//优惠券变化日志表
 	protected function add_scorelog($type,$mess,$balance,$member_id,$zz_id=0,$sk_id=0){
 		$data['type']=$type;
		$data['message']=$mess;
		$data['balance']=$balance;
		$data['member_id']=$member_id;
		$data['zz_id']=$zz_id;
		$data['sk_id']=$sk_id;
		$data['add_time']=now_time();
		return db('m_score_charge')->insert($data);
 	}
	//优惠券生成器记录
	protected function add_jljlog($type,$jlj,$id,$money){
		$row2['type'] = $type; 
		$row2['jlj'] = $jlj;
		$row2['user_id'] = $id;
		$row2['z_money'] = $money;
		$row2['add_time'] = now_time();
		$res = db('m_jljlog')->insert($row2);
		if($res){
			return true;  
		}else{
			return false; 
		} 
	}
	//增加转入日志
	protected function add_log($user_id,$num){
		$data['u_id']=$user_id;
		$data['balance']=$num;
		$data['order_type']="20";
		$data['message']="tailings转入优惠券";
		$data['add_time']=now_time();
		$res=Db::connect('db2')->name('log_user_score')->insert($data);
		return $res;
	}
	//*判断图片上传格式是否为图片 return返回文件后缀
	protected function getImagetype($filename) {
		$file = fopen($filename, 'rb');
		$bin = fread($file, 2);
		//只读2字节
		fclose($file);
		$strInfo = @unpack('C2chars', $bin);
		$typeCode = intval($strInfo['chars1'] . $strInfo['chars2']);
		// dd($typeCode);
		$fileType = '';
		switch ($typeCode) {
			case 255216 :
				$fileType = 'jpg';
				break;
			case 7173 :
				$fileType = 'gif';
				break;
			case 6677 :
				$fileType = 'bmp';
				break;
			case 13780 :
				$fileType = 'png';
				break;
			default :
				$fileType = 'error';
		}
		return $fileType;
	}

	protected function close_machine() {
		// 关闭所有过期的矿机
		$times = time() - 30 * 24 * 3600;
		db('member_machine')->where('add_time', '<', date('Y-m-d H:i:s', $times))->setField('status', 2);
	}

}
